package com.psnail.master.service.Impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.psnail.master.entity.FocusR;
import com.psnail.master.entity.Question;
import com.psnail.master.entity.Resource;
import com.psnail.master.entity.User;
import com.psnail.master.mapper.FocusRMapper;
import com.psnail.master.mapper.QuestionMapper;
import com.psnail.master.mapper.ResourceMapper;
import com.psnail.master.mapper.UserMapper;
import com.psnail.master.mapper.dao.QuestionDao;
import com.psnail.master.mapper.dao.UserDao;
import com.psnail.master.service.ResourceService;
import com.psnail.master.service.UserService;
import com.psnail.tools.Data2Html;
import com.psnail.tools.EmailTools;
import com.psnail.tools.IDTools;

@Service
public class ResourceServiceImpl implements ResourceService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private EmailTools ets;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private QuestionMapper questionMapper;
	@Autowired
	private FocusRMapper focusRMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserDao userDao;
	@Autowired
	private QuestionDao questionDao;
	@Autowired
	private UserService userService;
	@Autowired
	HttpServletRequest request;

	// 咨询问题解答的地址
	@Value("${email.resource.question}")
	private String questionAddress;
	// 咨询问题、远程部署评价邮件
	@Value("${email.resource.star}")
	private String starAddress;
	// 咨询问题金额
	@Value("${resource.question.money}")
	private String questionMoney;
	// 查看答案金额
	@Value("${resource.answer.money}")
	private String answerMoney;
	// 初级部署金额
	@Value("${resource.fuwu2.money}")
	private String fuwu2Money;
	// 中级部署金额
	@Value("${resource.fuwu3.money}")
	private String fuwu3Money;
	// 高级部署金额
	@Value("${resource.fuwu4.money}")
	private String fuwu4Money;
	// 站长邮箱
	@Value("${email.code.zhanzhang}")
	private String zhanzhang;
	// 管理员邮箱
	@Value("${email.code.guanliyuan}")
	private String guanliyuan;

	@Override
	public Map<String, Object> show(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Resource r = resourceMapper.selectByPrimaryKey(id);
			FocusR fr = new FocusR();
			fr.setUserId(user.getId());
			fr.setResourceId(id);
			fr.setWay(3);
			fr.setTime(new Date());
			int row = focusRMapper.insert(fr);
			if (row > 0) {
				result.put("status", 1);
				result.put("message", r.getAddress());
			} else {
				result.put("status", 0);
				result.put("message", "服务器错误！请联系站长");
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> like(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			FocusR fr = new FocusR();
			fr.setUserId(user.getId());
			fr.setResourceId(id);
			fr.setWay(1);
			fr.setTime(new Date());
			int row = focusRMapper.insert(fr);
			if (row > 0) {
				result.put("status", 1);
				result.put("message", "喜欢成功！");
			} else {
				result.put("status", 0);
				result.put("message", "服务器错误！请联系站长");
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> down(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Resource r = resourceMapper.selectByPrimaryKey(id);
			String downUrl = "";
			if (!"".equals(r.getGithub().trim())) {
				downUrl += "<a class='btn btn-sm btn-block' href='"
						+ r.getGithub() + "' target='_blank'>github下载</a>";
			}
			if (!"".equals(r.getGit().trim())) {
				downUrl += "<a class='btn btn-sm btn-block' href='"
						+ r.getGit() + "' target='_blank'>git下载</a>";
			}
			if (!"".equals(r.getBaiduyun().trim())) {
				downUrl += "<a class='btn btn-sm btn-block' href='"
						+ r.getBaiduyun() + "' target='_blank'>百度云下载</a>";
			}
			if (!"".equals(r.getOfficial().trim())) {
				downUrl += "<a class='btn btn-sm btn-block' href='"
						+ r.getOfficial() + "' target='_blank'>官方下载</a>";
			}
			FocusR fr = new FocusR();
			fr.setUserId(user.getId());
			fr.setResourceId(id);
			fr.setWay(2);
			fr.setTime(new Date());
			int row = focusRMapper.insert(fr);
			if (row > 0) {
				result.put("status", 1);
				result.put("message", downUrl);
			} else {
				result.put("status", 0);
				result.put("message", "服务器错误！请联系站长");
			}
		}
		return result;
	}

	@Override
	@Transactional
	public Map<String, Object> question(String id, String title) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			// 账户扣款
			result = userService.money("-", 6, new BigDecimal(questionMoney),
					user.getId());
			if ("1".equals(result.get("status").toString())) {// 钱包消费成功
				user = userDao.selectByEmail(user.getEmail());
				session.removeAttribute("user");
				session.setAttribute("user", user);
				String q_id = IDTools.createId();
				Question q = new Question();
				q.setId(q_id);
				q.setTitle(title);
				q.setContent("0");
				q.setChars(0);
				q.setStar(0);
				q.setWay(1);
				q.setResourceId(id);
				q.setUserId(user.getId());
				q.setTime(new Date());
				int row = questionMapper.insert(q);
				if (row > 0) {// 咨询记录成功
					Resource r = resourceMapper.selectByPrimaryKey(id);
					user = userMapper.selectByPrimaryKey(r.getUserId());
					String subject = "[蜗牛库]您的源码有一个￥" + questionMoney
							+ "元的咨询订单，请尽快解答。";
					String content = "源码项目：" + r.getTitle();
					content += "<br/><br/>请点击下面的链接去解答问题：<br/>";
					content += questionAddress + "?id=" + q_id;
					content += "<br/><br/>问题详情：<br/>" + title + "<br/>";
					try {
						ets.sendEmail(user.getEmail(), subject, content);
					} catch (Exception e) {
						logger.error("ResourceServiceImpl/question()发送邮件出现异常");
						result.put("status", 0);
						result.put("message",
								"咨询成功，但是您的问题通过邮件发送给源码作者过程中出现异常！请保留截图联系站长。");
					}
					result.put("status", 1);
					result.put("message",
							"您的问题已经通过邮件成功发送给源码作者！作者解答问题后，完整的解决方案会发送到您的注册邮箱，感谢您的支持。");
				} else {
					result.put("status", 0);
					result.put("message", "咨询问题失败！请联系站长");
				}
			}
		}
		return result;
	}

	@Override
	@Transactional
	public Map<String, Object> fuwu(String id, int way, String qq) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (qq == null || "".equals(qq)) {
			result.put("status", 0);
			result.put("message", "请输入您的QQ号码！以便作者联系您完成项目的部署。");
		} else if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else if (user.getVip() == 0 && user.getZanzhu() == 0) {
			result.put("status", 0);
			result.put("message", "你是普通用户！不能申请远程部署服务。");
		} else {
			String money = "";
			String title = "";
			if (way == 2) {
				money = fuwu2Money;
				title = "初级部署服务申请";
			} else if (way == 3) {
				money = fuwu3Money;
				title = "中级部署服务申请";
			} else if (way == 4) {
				money = fuwu4Money;
				title = "高级部署服务申请";
			}
			// 账户扣款
			result = userService.money("-", 7, new BigDecimal(money),
					user.getId());
			if ("1".equals(result.get("status").toString())) {// 钱包消费成功
				user = userDao.selectByEmail(user.getEmail());
				session.removeAttribute("user");
				session.setAttribute("user", user);
				String q_id = IDTools.createId();
				Question q = new Question();
				q.setId(q_id);
				q.setTitle(title);
				q.setContent("0");
				q.setChars(0);
				q.setStar(0);
				q.setWay(way);
				q.setResourceId(id);
				q.setUserId(user.getId());
				q.setTime(new Date());
				int row = questionMapper.insert(q);
				if (row > 0) {// 部署服务申请成功
					Resource r = resourceMapper.selectByPrimaryKey(id);
					user = userMapper.selectByPrimaryKey(r.getUserId());
					String subject = "[蜗牛库]您的源码有一个￥" + money + "元的" + title
							+ "订单，请尽快通过QQ联系用户完成远程部署服务。";
					String content = "源码项目：" + r.getTitle();
					content += "<br/><br/>用户QQ号码：" + qq;
					content += "<br/><br/>用户服务申请：￥" + money + "元的" + title;
					content += "<br/><br/>特别注意：远程部署服务完成后，需要用户评分后您才会收到此次部署所得服务费用，请将下面的链接复制后发送给用户完成评分。<br/>";
					content += starAddress + "?id=" + q_id;
					try {
						ets.sendEmail(user.getEmail(), subject, content);
					} catch (Exception e) {
						logger.error("ResourceServiceImpl/fuwu()发送邮件出现异常");
						result.put("status", 0);
						result.put("message",
								"远程部署服务申请成功，但是您的申请通过邮件发送给源码作者过程中出现异常！请保留截图联系站长。");
					}
					result.put("status", 1);
					result.put("message",
							"您的远程部署服务申请已经通过邮件成功发送给源码作者！作者会尽快通过QQ联系您完成项目的部署，感谢您的支持。");
				} else {
					result.put("status", 0);
					result.put("message", "远程部署服务申请失败！请联系站长");
				}
			}
		}
		return result;
	}

	@Override
	public String detail2Html(String id) {
		return Data2Html.resourceDetailToHtml(
				resourceMapper.selectByPrimaryKey(id),
				questionDao.selectAllAnswer(id), questionMoney, answerMoney,
				fuwu2Money, fuwu3Money, fuwu4Money);
	}

	@Override
	@Transactional
	public Map<String, Object> daan(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			// 账户扣款
			result = userService.money("-", 8, new BigDecimal(answerMoney),
					user.getId());
			if ("1".equals(result.get("status").toString())) {// 钱包消费成功
				user = userDao.selectByEmail(user.getEmail());
				session.removeAttribute("user");
				session.setAttribute("user", user);
				Question q = questionMapper.selectByPrimaryKey(id);
				Resource r = resourceMapper.selectByPrimaryKey(q
						.getResourceId());
				String subject = "[蜗牛库]消费记录：￥1.0查看问题答案";
				String content = "源码项目：" + r.getTitle();
				content += "<br/><br/>问题：" + q.getTitle();
				content += "<br/><br/>解答：" + q.getContent();
				try {
					ets.sendEmail(user.getEmail(), subject, content);
				} catch (Exception e) {
					logger.error("ResourceServiceImpl/daan()发送邮件出现异常");
					result.put("status", 0);
					result.put("message", "答案通过邮件发送到您的注册邮箱过程中出现异常！请保留截图联系站长。");
				}
				result.put("status", 1);
				result.put("message", "答案已经通过邮件发送到您的注册邮箱！请注意查收。");
			}
		}
		return result;
	}

	@Override
	@Transactional
	public void daanTicheng(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		Question q = questionMapper.selectByPrimaryKey(id);
		// 资源拥有者获得一半金额
		Resource r = resourceMapper.selectByPrimaryKey(q.getResourceId());
		result = userService.money("+", 9,
				new BigDecimal(answerMoney).divide(new BigDecimal(2)),
				r.getUserId());
		if ("1".equals(result.get("status").toString())) {// 答案提成成功
			String subject = "[蜗牛库]提成：账户增加￥"
					+ new BigDecimal(answerMoney).divide(new BigDecimal(2))
					+ "元";
			String content = "网站用户：" + user.getName() + "，花费 ￥" + answerMoney
					+ " 查看了您的源码《" + r.getTitle() + "》中问题的答案，您获得了"
					+ new BigDecimal(answerMoney).divide(new BigDecimal(2))
					+ "元的提成。";
			content += "<br/><br/>查看的问题：<br/>" + q.getTitle();
			try {
				ets.sendEmail(userMapper.selectByPrimaryKey(r.getUserId())
						.getEmail(), subject, content);
			} catch (Exception e) {
				logger.error("ResourceServiceImpl/daan()发送邮件出现异常");
			}
		}
	}

	@Override
	public Map<String, Object> getQuestionById(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (id == null || "".equals(id)) {
			result.put("status", 0);
			result.put("message", "没有此问题！");
		} else {
			Question q = questionMapper.selectByPrimaryKey(id);
			Resource r = resourceMapper.selectByPrimaryKey(q.getResourceId());
			result.put("status", 1);
			result.put("message", "查询成功");
			result.put("resource", r.getTitle());
			if (q.getWay() == 1) {
				result.put("way", q.getWay());
				result.put("money", questionMoney);
				result.put("title", q.getTitle());
			} else if (q.getWay() == 2) {
				result.put("way", q.getWay());
				result.put("money", fuwu2Money);
				result.put("title", q.getTitle());
			} else if (q.getWay() == 3) {
				result.put("way", q.getWay());
				result.put("money", fuwu3Money);
				result.put("title", q.getTitle());
			} else if (q.getWay() == 4) {
				result.put("way", q.getWay());
				result.put("money", fuwu4Money);
				result.put("title", q.getTitle());
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> answer(String id, String content) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (id == null || "".equals(id)) {
			result.put("status", 0);
			result.put("message", "没有此问题资源！");
		} else if (content == null || "".equals(content)) {
			result.put("status", 0);
			result.put("message", "请输入答案！");
		} else if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Question q = questionMapper.selectByPrimaryKey(id);
			Resource r = resourceMapper.selectByPrimaryKey(q.getResourceId());
			if (user.getId().equals(
					userMapper.selectByPrimaryKey(r.getUserId()).getId())) {
				q.setContent(content);
				q.setChars(content.length());
				int row = questionMapper.updateByPrimaryKey(q);
				if (row > 0) {
					String subject = "[蜗牛库]待评价解答问题";
					String c = "您好，您咨询的问题，有了最新的解答，请点击下方链接去评分：<br/>"
							+ starAddress + "?id=" + id;
					c += "<br/><br/>咨询源码：" + r.getTitle();
					c += "<br/>咨询问题：<br/>" + q.getTitle();
					c += "<br/>问题解答：<br/>" + content;
					try {
						ets.sendEmail(
								userMapper.selectByPrimaryKey(q.getUserId())
										.getEmail(), subject, c);
					} catch (Exception e) {
						logger.error("ResourceServiceImpl/answer()发送邮件出现异常");
					}
					result.put("status", 1);
					result.put("id", q.getResourceId());
					result.put("message", "答案发送成功！待用户评价后，您将根据评价获得对应的酬劳。");
				} else {
					result.put("status", 0);
					result.put("message", "解答问题失败！");
				}
			} else {
				result.put("status", 0);
				result.put("message", "你没有权限解答此问题！");
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> star(String id, String score) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (id == null || "".equals(id)) {
			result.put("status", 0);
			result.put("message", "您没有申请此服务！");
		} else if (score == null || "".equals(score)
				|| Integer.valueOf(score) <= 0 || Integer.valueOf(score) > 5) {
			result.put("status", 0);
			result.put("message", "请先进行正确的评分操作！");
		} else if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Question q = questionMapper.selectByPrimaryKey(id);
			if (q.getStar() > 0 && q.getStar() <= 5) {
				result.put("status", 0);
				result.put("message", "该服务已经评分，无法再次评分！");
			} else if (!user.getId().equals(q.getUserId())
					&& !zhanzhang.contains(user.getEmail())
					&& !guanliyuan.contains(user.getEmail())) {
				result.put("status", 0);
				result.put("message", "你没有权限进行评分！");
			} else {
				q.setStar(Integer.valueOf(score));
				int row = questionMapper.updateByPrimaryKey(q);
				if (row > 0) {
					Resource r = resourceMapper.selectByPrimaryKey(q
							.getResourceId());
					user = userMapper.selectByPrimaryKey(r.getUserId());
					String money = "";
					String title = "";
					if (q.getWay() == 1) {
						money = questionMoney;
						title = "技术咨询";
					} else if (q.getWay() == 2) {
						money = fuwu2Money;
						title = "初级部署服务申请";
					} else if (q.getWay() == 3) {
						money = fuwu3Money;
						title = "中级部署服务申请";
					} else if (q.getWay() == 4) {
						money = fuwu4Money;
						title = "高级部署服务申请";
					}
					BigDecimal choulao = new BigDecimal(money)
							.multiply(new BigDecimal(score)
									.multiply(new BigDecimal("0.2")));
					String subject = "[蜗牛库]评分通知";
					String c = "源码作者 " + user.getName() + " ，您好：";
					c += "<br/>您提供的服务：￥" + money + "的" + title + "，获得了" + score
							+ "星评价，根据评价对应标准，您的账户将增加￥" + choulao + "的酬劳。";
					try {
						ets.sendEmail(user.getEmail(), subject, c);
					} catch (Exception e) {
						logger.error("ResourceServiceImpl/star()发送邮件出现异常");
					}
					result.put("status", 1);
					result.put("id", q.getResourceId());
					result.put("choulao", choulao);
					result.put("message", "评分成功！通知邮件已发送给源码作者，感谢您的评分。");
				} else {
					result.put("status", 0);
					result.put("message", "评分失败！");
				}
			}
		}
		return result;
	}

	@Override
	public void ticheng(String id, BigDecimal money) {
		Map<String, Object> result = new HashMap<String, Object>();
		Question q = questionMapper.selectByPrimaryKey(id);
		Resource r = resourceMapper.selectByPrimaryKey(q.getResourceId());
		result = userService.money("+", 10, money, r.getUserId());
		if ("1".equals(result.get("status").toString())) {// 提成成功
			String subject = "[蜗牛库]提成：账户增加￥" + money + "元";
			String content = "您获得了" + money + "元的提成。";
			try {
				ets.sendEmail(userMapper.selectByPrimaryKey(r.getUserId())
						.getEmail(), subject, content);
			} catch (Exception e) {
				logger.error("ResourceServiceImpl/ticheng()发送邮件出现异常");
			}
		}
	}

}